package com.neo.androidcommon.mytest;

import android.support.annotation.NonNull;

import com.neo.androidcommon.CommonUtils.LogUtil;

import java.util.ArrayDeque;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Administrator on 2018/9/14.
 */

public class ThreadPoolTest {
    private static final int CORE_POOL_SIZE = 5;
    private static final int MAXIMUM_POOL_SIZE = 128;
    private static final int KEEP_ALIVE = 10;
    //线程队列
    private static final BlockingDeque<Runnable> sWorkQueue = new LinkedBlockingDeque<>(10);
    //    线程工厂
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        @Override
        public Thread newThread(@NonNull Runnable r) {
            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        }
    };
    //线程池
    private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor
            (CORE_POOL_SIZE,
                    MAXIMUM_POOL_SIZE,
                    KEEP_ALIVE,
                    TimeUnit.SECONDS,
                    sWorkQueue,
                    sThreadFactory);

    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
    //    默认的 任务调度 是 顺序执行
    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

    private static class SerialExecutor implements Executor {

        final ArrayDeque<Runnable> mTasks = new ArrayDeque<>();
        Runnable mActive;

        @Override
        public void execute(@NonNull final Runnable command) {

            mTasks.offer(new Runnable() {
                @Override
                public void run() {
                    try {
                        command.run();
                    } finally {
                        scheduleNext();
                    }

                }
            });

            if (mActive == null) {
                scheduleNext();
            }
        }

        protected synchronized void scheduleNext() {

            if ((mActive = mTasks.poll()) != null) {
//                将 认为交给 THREAD_POOL_EXECUTOR 执行
                THREAD_POOL_EXECUTOR.execute(mActive);

            }


        }

    }


}
